<template>
	<view class="booy" style="background-color:gainsboro;height: 100vh; width: 100vw;">
		<view class="calendar-content" v-if="showCalendar">
			<view>
				<!-- 插入模式 -->
				<uni-calendar class="uni-calendar--hook" disabledBefore :selected="info.selected" :showMonth="false"
					@change="handleDateChange" @monthSwitch="monthSwitch" />
			</view>
		</view>
		<view class="container">
			<view @click="tptime(list.id)" class="user-info" v-for="(list,index) in cardlist  " :key="list.name">
				<image class="avatar" :src="url()+list.imgpath" </image>
					<view class="name">
						<text>{{list.name}}</text>
					</view>
					<view class="time-slots">
						<image class="imges" src="/static/jk/sj.png"></image><text>{{list.size}}个时段</text>
					</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		nextTick
	} from 'vue';
	import {
		onLoad,
		onShow
	}
	from '@dcloudio/uni-app';
	import {
		gettoday,
		getperiod,
		checkDataForDate,
		url
	} from '@/request/api.js'
	//获取今天预约时间的家政
	onMounted(async () => {
		// 获取当前日期
		const currentDate = new Date();

		// 获取今天的年、月、日
		const year = currentDate.getFullYear(); // 获取年份
		const month = currentDate.getMonth() + 1; // 获取月份，月份从0开始，所以需要+1
		const day = currentDate.getDate(); // 获取日期

		// 构建一个字符串，包含年月日
		const today = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;

		// 构建要传递给gettoday函数的数据对象
		const data = {
			'date': today // 今天的日期字符串
		};
		showdate(data)
	});
	//显示家政名片
	async function showdate(data) {
		try {
			const response = await gettoday(data);
            console.log(response)
			// 使用map创建一个包含Promise的数组
			const promises = response.data.data.map(item => {
				const inform = {
					'id': item.id // 确保这里正确地引用了item的id属性
				};
				return getperiod(inform).then(req => {
					console.log("req", req);
					return {
						id: item.id,
						name: item.name,
						imgpath: item.imgpath,
						size: req.data.data.length
					};
				});
			});

			// 使用Promise.all等待所有Promise完成
			cardlist.value = await Promise.all(promises);
		} catch (error) {
			console.error("Error fetching data:", error);
		}
	}
	const showCalendar = ref(false);
	const info = ref({
		lunar: true,
		range: true,
		insert: false,
		selected: [],
	});

	const calendar = ref(null);
	const cardlist = ref([])
	async function queryDataForMonth() {
	    const currentDate = new Date();
	    const lastDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
	    const datesWithData = [];
	
	    let startDay = currentDate.getDate() < lastDayOfMonth.getDate() ? currentDate.getDate() + 1 : currentDate.getDate();
	
	    for (let day = startDay; day <= lastDayOfMonth.getDate(); day++) {
	        const targetDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), day);
	        const formattedDate = targetDate.toISOString().split('T')[0];
	        try {
	            const dateObj = { "date": formattedDate };
	            const data = await checkDataForDate(dateObj);
	            console.log("Data for", formattedDate, data);
	
	            if (data.data.msg != 300) {
	                datesWithData.push(formattedDate); // 直接使用 formattedDate，假设 getDate 函数不是必需的
	            }
	        } catch (error) {
	            console.error("Error checking data for date:", targetDate, error);
	        }
	    }
	
	    return datesWithData;
	}
	onMounted(() => {
		nextTick(() => {
			showCalendar.value = true; // 在DOM更新后，设置showCalendar的值为true，以显示日历
		});

		setTimeout(async () => { // 使用setTimeout来延迟执行代码，确保某些异步操作完成后再执行
			const datesWithData = await queryDataForMonth(); // 查询从今天到月末的数据
			console.log("datesWithData", datesWithData)
			info.value.selected = datesWithData.map(dateStr => {
				// 将日期字符串转换为Date对象
				const date = new Date(dateStr);
				// 减去一天
				date.setDate(date.getDate());
				// 将Date对象转换回字符串格式
				const newDateStr =
					`${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
				// 创建新的记录并返回
				return {
					date: newDateStr,
					info: '可预约' // 标记信息为“可预约”
				};
			});
			// 设置info对象的其他属性
			info.value.date = getDate(new Date(), -30).fullDate; // 设置info对象的date属性为当前日期前30天的完整日期字符串
			info.value.startDate = getDate(new Date(), -60)
				.fullDate; // 设置info对象的startDate属性为当前日期前60天的完整日期字符串
			info.value.endDate = getDate(new Date(), 30)
				.fullDate; // 设置info对象的endDate属性为当前日期后30天的完整日期字符串
		}, 2000); // 延迟2000毫秒（2秒）后执行上述操作
	});

	function getDate(date, AddDayCount = 0) {
		if (!date) {
			date = new Date()
		}
		if (typeof date !== 'object') {
			date = date.replace(/-/g, '/')
		}
		const dd = new Date(date)

		dd.setDate(dd.getDate() + AddDayCount) // 获取AddDayCount天后的日期

		const y = dd.getFullYear()
		const m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1 // 获取当前月份的日期，不足10补0
		const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号，不足10补0
		return {
			fullDate: y + '-' + m + '-' + d,
			year: y,
			month: m,
			date: d,
			day: dd.getDay()
		}
	}


	//跳转预约详情
	function tptime(id) {
		uni.navigateTo({
			url: `/pages/user/details/subscribe?id=${id}`
		})
	}
	//点击时间段获取是否可以预约
	function handleDateChange(event) {
		const date = {
			"date": event.fulldate
		}
		showdate(date)
       
	}

	function confirm(e) {
		console.log('confirm 返回:', e);
	}

	function monthSwitch(e) {
		console.log('monthSwitchs 返回:', e);
	}
</script>
<style lang="scss">
	.imges {
		width: 15px;
		height: 15px;
		margin-right: 8px;
	}

	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		margin-top: 20px;
	}

	.user-info {
		margin: 5px;
		padding: 5px;
		width: 85%;
		background-color: white;
		border-radius: 10px;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
	}

	.avatar {
		width: 50px;
		height: 50px;
		border-radius: 50%;
		/* 圆形头像 */
		margin-right: 10px;
	}

	.name {
		height: 0px;
		transform: translate(70px, -40px);
		font-size: 16px;
		font-weight: bold;

	}

	.time-slots {
		height: 0px;
		font-size: 16px;
		color: #666;
		transform: translate(220px, -40px);
	}

	.example-body {
		display: flex;
		flex-direction: row;
	}

	.calendar-button {
		flex: 1;
		font-weight: bold;
		font-size: 32rpx;
	}
</style>